package com.zhai.domain.strategy.service.rule.tree.impl;

import com.zhai.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.zhai.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.zhai.domain.strategy.repository.IStrategyRepository;
import com.zhai.domain.strategy.service.armory.IStrategyDispatch;
import com.zhai.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.zhai.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: 库存扣减节点
 * @ClassName: RuleLockLogicTreeNode
 * @Author: zhaiyongxin
 * @Date: 2025/2/5 15:00
 * @Version: 1.0
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {
    
    @Resource
    private IStrategyDispatch strategyDispatch;
    @Resource
    private IStrategyRepository strategyRepository;
    
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, Date endDateTime, String ruleValue) {
        log.info("规则过滤-库存扣减 userId:{}, strategyId:{}, awardId:{}", userId, strategyId, awardId);
        
        // 1.扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);
        // 2.库存扣减成功，放入延迟队列进行延迟消费，避免对数据库造成太大压力
        if (status) {
            log.info("规则过滤-库存扣减-成功 userId:{}, strategyId:{}", userId, strategyId);

            //redis 存入延迟队列 定时任务读取队列进行数据库更新
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                            .awardId(awardId)
                            .strategyId(strategyId)
                            .build());
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }
        // 3.库存扣减失败 可能没有库存了 进行兜底奖励
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
